package com.swust.dumpling.commons.file.excel;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

/**
 * 被解析类得有一个无参构造器
 * */
public class ExcelMaking {
	
	public static void make(File file , List<?> list , String... title) 
	{
		if ( ! file.exists() ) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		WritableWorkbook wwb = null;
		try {
			wwb = Workbook.createWorkbook(file);
		} catch (IOException e1) {
			e1.printStackTrace();
			return;
		}
		WritableSheet sheet = wwb.createSheet("sheet0", 0);
		WritableCellFormat wcf = new WritableCellFormat();
		Label label = null;
		Class<?> obj = null;
		Field[] field = null;
		Method method;
		String name = null;
		
		for ( int i = 0 ; i < list.size() ; i ++ ) {
			obj = list.get(i).getClass();
			field = obj.getDeclaredFields();
			
			int cou = 0;
			
			for ( int j = 0 ; j < field.length ; j ++ ) {
				name = field[j].getName();
				name = "get" + name.substring(0 , 1).toUpperCase() + name.substring(1);
				method = null;
				//该方法对第一个无效,也将对接下来的所有都无效.
				try {
					method = obj.getMethod(name);
				} catch (NoSuchMethodException e) {
					//没找到这个方法----方法必为公共类方法
				} catch (SecurityException e) {
					//暂时不知道原因----2014年2月20日17:16:51
				}
				try {
					//Label( 列值 , 行值 , 数据 , WCF );
					label = new Label(cou , i+1 , (String) method.invoke(obj), wcf );
					cou ++;
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
				try {
					sheet.addCell(label);
				} catch (RowsExceededException e) {
					e.printStackTrace();
				} catch (WriteException e) {
					e.printStackTrace();
				}
			}
		}
		try {
			wwb.write();
			wwb.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
	}

}
